<?php

namespace App\Validate\Web;

use App\Validate\BaseValidate;
use Illuminate\Support\Facades\Auth;

class TaskStoreValidate extends BaseValidate
{
    protected $rules = [];// 规则

    protected $message = [];// 自定义消息

    public function __construct($request)
    {
        parent::__construct($request);

        $this->rules = [
            'type' => 'required|numeric',
            'title' => 'required',
            'market_image' => 'required',
            'content' => 'required',
            'commission_rate' => 'required',
            'price_last_coupon' => 'required|numeric',
            'price' => 'required|numeric|min:0.5',
            'total_num' => 'required|numeric|min:20',
            'remark' => 'nullable|string|max:20',
        ];
        $this->message = [
            'type.required' => '请选择任务类型',
            'type.numeric' => '请选择任务类型',
            'title.required' => '请输入产品标题',
            'market_image.required' => '请上传营销主图',
            'content.required' => '请输入文案',
            'commission_rate.required' => '请输入佣金比例',
            'price_last_coupon.required' => '请输入券后价',
            'price.required' => '请输入任务单价',
            'price.min' => '任务单价不能小于0.5',
            'total_num.required' => '请输入任务数量',
            'total_num.min' => '任务数量不能小于20',
            'remark.max' => '备注内容限制在20个字以内',
        ];
    }

    protected function customValidate()
    {
        $send_date  = $this->requestData['send_date'];
        $type       = $this->requestData['type'];
        $price      = $this->requestData['price'];
        $total_num  = $this->requestData['total_num'];
        $union_list = json_decode($this->requestData['union_list'],1);

        if($type == 1 && $send_date == 4 && $price < 1){
            $this->validator->errors()->add('send_date', '加急单最低1元起');
            return false;
        }

        if($type == 1 && $send_date == 4 && $total_num < 30){
            $this->validator->errors()->add('send_date', '加急单最少30任务数量');
            return false;
        }

        if($type == 2 && empty($union_list)){
            $this->validator->errors()->add('union_list', '请选择联盟');
            return false;
        }

        if($type == 1 && count($union_list) > 10){
            $this->validator->errors()->add('union_list', '黑名单不可超过10个联盟，请修改');
            return false;
        }

        $user = Auth::user();
        if($type == 2){//指派
            $total_price = 0;
            foreach ($union_list as $k => $v){
                $total_price += $v['offer_price'];
            }

            if($total_price > $user->amount){
                $this->validator->errors()->add('user_amount', '用户余额不足,无法发布任务,请先充值');

                return false;
            }
        }else{
            if($price * $total_num > $user->amount){
                $this->validator->errors()->add('user_amount', '用户余额不足,无法发布任务,请先充值');

                return false;
            }
        }
    }
}
